<template>
  <div>
    <!-- 账户资金信息卡片 -->
    <div class="accountInfoSection" style="padding: 10px;">
      <a-row :gutter="24">
        <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card 
            :bordered="false" 
            :loading="accountInfoLoading"
            style="margin-bottom: 16px;"
          >
            <template #title>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 16px; font-weight: bold;">账户资金概览</span>
                <span v-if="latestSettlementDate" style="color: #666; font-size: 14px; text-align: center; flex: 1;">
                  最新结算日期: {{ latestSettlementDate }}
                </span>
              </div>
            </template>
            <a-row :gutter="16">
              <a-col 
                v-for="account in accountInfoList" 
                :key="account.accountCode" 
                :xl="6" :lg="8" :md="12" :sm="12" :xs="24"
              >
                <div class="accountCard" :class="{ 'high-risk': account.riskRatio > 0.8 }">
                  <div class="accountHeader">
                    <span class="accountCode">{{ account.accountCode }}</span>
                    <span v-if="account.riskRatio > 0.8" class="riskWarning">高风险</span>
                  </div>
                  <div class="accountContent">
                    <div class="infoItem">
                      <span class="label">可用资金:</span>
                      <span class="value amount">{{ formatAmount(account.availableFunds) }}</span>
                    </div>
                    <div class="infoItem">
                      <span class="label">风险度:</span>
                      <span class="value risk-ratio" :class="getRiskRatioClass(account.riskRatio)">
                        {{ formatRiskRatio(account.riskRatio) }}
                      </span>
                    </div>
                  </div>
                </div>
              </a-col>
              <a-col v-if="accountInfoList.length === 0" :xl="24" :lg="24" :md="24" :sm="24" :xs="24" style="text-align: center; padding: 20px;">
                <span style="color: #999;">暂无账户资金数据</span>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <!-- 资金曲线图表区域 - 简化版 -->
    <div style="padding: 0 10px 10px 10px; margin-bottom: 16px;">
      <div class="equity-chart-container" style="width: 100%; height: 300px;">
        <div ref="equityChartContainer" style="width: 100%; height: 100%;"></div>
      </div>
    </div>
    
    <div class="pageHeaderContent">
      <div class="avatar">
        <a-avatar size="large" :src="currentUser.avatar" />
      </div>
      <div class="content">
        <div class="contentTitle">
          早安，
          {{ currentUser.name }}
          ，祝你开心每一天！
        </div>
        <div>{{ currentUser.title }} |{{ currentUser.group }}</div>
      </div>
      <div class="extraContent">
        <div class="statItem">
          <a-statistic title="项目数" :value="56" />
        </div>
        <div class="statItem">
          <a-statistic title="团队内排名" :value="8" suffix="/ 24" />
        </div>
        <div class="statItem">
          <a-statistic title="项目访问" :value="2223" />
        </div>
      </div>
    </div>

    <div style="padding: 10px">
      <a-row :gutter="24">
        <a-col :xl="16" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card
            class="projectList"
            :style="{ marginBottom: '24px' }"
            title="进行中的项目"
            :bordered="false"
            :loading="false"
            :body-style="{ padding: 0 }"
          >
            <template #extra>
              <a href=""> <span style="color: #1890ff">全部项目</span> </a>
            </template>
            <a-card-grid
              v-for="item in projectNotice"
              :key="item.id"
              class="projectGrid"
            >
              <a-card
                :body-style="{ padding: 0 }"
                style="box-shadow: none"
                :bordered="false"
              >
                <a-card-meta :description="item.description" class="w-full">
                  <template #title>
                    <div class="cardTitle">
                      <a-avatar size="small" :src="item.logo" />
                      <a :href="item.href">
                        {{ item.title }}
                      </a>
                    </div>
                  </template>
                </a-card-meta>
                <div class="projectItemContent">
                  <a :href="item.memberLink">
                    {{ item.member || "" }}
                  </a>
                  <span class="datetime" ml-2 :title="item.updatedAt">
                    {{ item.updatedAt }}
                  </span>
                </div>
              </a-card>
            </a-card-grid>
          </a-card>
          <a-card
            :body-style="{ padding: 0 }"
            :bordered="false"
            class="activeCard"
            title="动态"
            :loading="false"
          >
            <a-list :data-source="activities" class="activitiesList">
              <template #renderItem="{ item }">
                <a-list-item :key="item.id">
                  <a-list-item-meta>
                    <template #title>
                      <span>
                        <a class="username">{{ item.user.name }}</a
                        >&nbsp;
                        <span class="event">
                          <span>{{ item.template1 }}</span
                          >&nbsp;
                          <a href="" style="color: #1890ff">
                            {{ item?.group?.name }} </a
                          >&nbsp; <span>{{ item.template2 }}</span
                          >&nbsp;
                          <a href="" style="color: #1890ff">
                            {{ item?.project?.name }}
                          </a>
                        </span>
                      </span>
                    </template>
                    <template #avatar>
                      <a-avatar :src="item.user.avatar" />
                    </template>
                    <template #description>
                      <span class="datetime" :title="item.updatedAt">
                        {{ item.updatedAt }}
                      </span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-col>
        <a-col :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card
            :style="{ marginBottom: '24px' }"
            title="快速开始 / 便捷导航"
            :bordered="false"
            :body-style="{ padding: 0 }"
          >
            <EditableLinkGroup />
          </a-card>
          <a-card
            :style="{ marginBottom: '24px' }"
            :bordered="false"
            title="XX 指数"
          >
            <div class="chart">
              <div ref="radarContainer" />
            </div>
          </a-card>
          <a-card
            :body-style="{ paddingTop: '12px', paddingBottom: '12px' }"
            :bordered="false"
            title="团队"
          >
            <div class="members">
              <a-row :gutter="48">
                <a-col
                  v-for="item in projectNotice"
                  :key="`members-item-${item.id}`"
                  :span="12"
                >
                  <a :href="item.href">
                    <a-avatar :src="item.logo" size="small" />
                    <span class="member">{{ item.member }}</span>
                  </a>
                </a-col>
              </a-row>
            </div>
          </a-card>
        </a-col>
      </a-row>
      

    </div>
  </div>
</template>

<script>
import {
  Statistic,
  Row,
  Col,
  Card,
  CardGrid,
  CardMeta,
  List,
  ListItem,
  ListItemMeta,
  Avatar,
} from "ant-design-vue";
import 'ant-design-vue/dist/reset.css';

export default {
  components: {
    AStatistic: Statistic,
    ARow: Row,
    ACol: Col,
    ACard: Card,
    ACardGrid: CardGrid,
    ACardMeta: CardMeta,
    AList: List,
    AListItem: ListItem,
    AListItemMeta: ListItemMeta,
    AAvatar: Avatar,
  },
};
</script>

<style scoped>
/* 账户信息卡片样式 */
.accountInfoSection {
  margin-bottom: 16px;
}

.accountCard {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.accountCard:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.accountCard.high-risk {
  background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 15px rgba(255, 65, 108, 0.3);
  }
  50% {
    box-shadow: 0 4px 25px rgba(255, 65, 108, 0.6);
  }
  100% {
    box-shadow: 0 4px 15px rgba(255, 65, 108, 0.3);
  }
}

.accountHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.accountCode {
  font-size: 18px;
  font-weight: bold;
}

.riskWarning {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  animation: blink 1s infinite alternate;
}

@keyframes blink {
  0% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

.accountContent {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.infoItem {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.infoItem .label {
  font-size: 14px;
  opacity: 0.9;
}

.infoItem .value {
  font-size: 16px;
  font-weight: bold;
}

.infoItem .value.amount {
  font-size: 18px;
}

.infoItem .value.risk-ratio.high {
  color: #ff6b6b;
}

.infoItem .value.risk-ratio.medium {
  color: #ffe66d;
}

.infoItem .value.risk-ratio.low {
  color: #4ecdc4;
}
</style>


<script setup>
import { Radar } from "@antv/g2plot";
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import EditableLinkGroup from "./editable-link-group.vue";
import { listFutureAccountDaily } from '@/api/kylin/futureAccountDaily';
import { getAllFutureAccounts } from '@/api/kylin/futureAccount';

// 账户信息相关状态
const accountInfoList = ref([]);
const latestSettlementDate = ref('');
const accountInfoLoading = ref(false);
const accountList = ref([]);

// 风险度格式化函数
const formatRiskRatio = (value) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0.00%';
  }
  return (Number(value) * 100).toFixed(2) + '%';
};

// 获取风险度样式类
const getRiskRatioClass = (riskRatio) => {
  if (riskRatio > 0.8) return 'high';
  if (riskRatio > 0.6) return 'medium';
  return 'low';
};

// 加载期货账户列表
const loadAccountList = async () => {
  try {
    const response = await getAllFutureAccounts();
    accountList.value = response?.data || [];
    return accountList.value;
  } catch (error) {
    console.error('获取期货账户列表失败:', error);
    return [];
  }
};

// 获取最新结算日期的账户数据
const fetchLatestAccountData = async () => {
  accountInfoLoading.value = true;
  try {
    // 先获取所有账户
    const accounts = await loadAccountList();
    if (accounts.length === 0) {
      accountInfoList.value = [];
      latestSettlementDate.value = '';
      return;
    }

    // 创建查询参数，获取足够多的数据以便找到最大日期
    const params = {
      pageNum: 1,
      pageSize: 1000, // 获取足够多的数据
      accountCode: undefined, // 不限制账户
      beginDate: undefined,
      endDate: undefined
    };

    const response = await listFutureAccountDaily(params);
    if (response.code === 200) {
      const data = response.data?.rows || response.rows || [];
      
      // 按日期分组
      const groupedByDate = {};
      data.forEach(item => {
        if (!groupedByDate[item.settlementDate]) {
          groupedByDate[item.settlementDate] = [];
        }
        groupedByDate[item.settlementDate].push(item);
      });

      // 找到最大的日期
      const dates = Object.keys(groupedByDate).sort();
      if (dates.length > 0) {
        const maxDate = dates[dates.length - 1];
        latestSettlementDate.value = maxDate;
        
        // 获取最大日期的所有账户数据
        const latestData = groupedByDate[maxDate];
        
        // 创建账户代码到数据的映射
        const accountDataMap = {};
        latestData.forEach(item => {
          accountDataMap[item.accountCode] = item;
        });

        // 确保每个账户都有数据展示
        accountInfoList.value = accounts.map(account => {
          const accountData = accountDataMap[account.accountCode] || {
            accountCode: account.accountCode,
            availableFunds: 0,
            riskRatio: 0
          };
          return accountData;
        });
      } else {
        accountInfoList.value = [];
        latestSettlementDate.value = '';
      }
    }
  } catch (error) {
    console.error('获取最新账户数据失败:', error);
    ElMessage.error('获取账户数据失败，请稍后重试');
    accountInfoList.value = [];
    latestSettlementDate.value = '';
  } finally {
    accountInfoLoading.value = false;
  }
};

defineOptions({
  name: "DashBoard",
});

const currentUser = {
  avatar: "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
  name: "吴彦祖",
  userid: "00000001",
  email: "antdesign@alipay.com",
  signature: "海纳百川，有容乃大",
  title: "交互专家",
  group: "蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED",
};

const projectNotice = [
  {
    id: "xxx1",
    title: "Alipay",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/WdGqmHpayyMjiEhcKoVE.png",
    description: "那是一种内在的东西，他们到达不了，也无法触及的",
    updatedAt: "几秒前",
    member: "科学搬砖组",
    href: "",
    memberLink: "",
  },
  {
    id: "xxx2",
    title: "Angular",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/zOsKZmFRdUtvpqCImOVY.png",
    description: "希望是一个好东西，也许是最好的，好东西是不会消亡的",
    updatedAt: "6 年前",
    member: "全组都是吴彦祖",
    href: "",
    memberLink: "",
  },
  {
    id: "xxx3",
    title: "Ant Design",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/dURIMkkrRFpPgTuzkwnB.png",
    description: "城镇中有那么多的酒馆，她却偏偏走进了我的酒馆",
    updatedAt: "几秒前",
    member: "中二少女团",
    href: "",
    memberLink: "",
  },
  {
    id: "xxx4",
    title: "Ant Design Pro",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/sfjbOqnsXXJgNCjCzDBL.png",
    description: "那时候我只会想自己想要什么，从不想自己拥有什么",
    updatedAt: "6 年前",
    member: "程序员日常",
    href: "",
    memberLink: "",
  },
  {
    id: "xxx5",
    title: "Bootstrap",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/siCrBXXhmvTQGWPNLBow.png",
    description:
      "凛冬将至",
    updatedAt: "6 年前",
    member: "高逼格设计天团",
    href: "",
    memberLink: "",
  },
  {
    id: "xxx6",
    title: "React",
    logo: "https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png",
    description: "生命就像一盒巧克力，结果往往出人意料",
    updatedAt: "6 年前",
    member: "骗你来学计算机",
    href: "",
    memberLink: "",
  },
];

const activities = [
  {
    id: "trend-1",
    updatedAt: "几秒前",
    user: {
      name: "曲丽丽",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
    },
    group: {
      name: "高逼格设计天团",
      link: "http://github.com/",
    },
    project: {
      name: "六月迭代",
      link: "http://github.com/",
    },
    template1: "在",
    template2: "新建项目",
  },
  {
    id: "trend-2",
    updatedAt: "几秒前",
    user: {
      name: "付小小",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/cnrhVkzwxjPwAaCfPbdc.png",
    },
    group: {
      name: "高逼格设计天团",
      link: "http://github.com/",
    },
    project: {
      name: "六月迭代",
      link: "http://github.com/",
    },
    template1: "在",
    template2: "新建项目",
  },
  {
    id: "trend-3",
    updatedAt: "几秒前",
    user: {
      name: "林东东",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/gaOngJwsRYRaVAuXXcmB.png",
    },
    group: {
      name: "中二少女团",
      link: "http://github.com/",
    },
    project: {
      name: "六月迭代",
      link: "http://github.com/",
    },
    template1: "在",
    template2: "新建项目",
  },
  {
    id: "trend-4",
    updatedAt: "几秒前",
    user: {
      name: "周星星",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/WhxKECPNujWoWEFNdnJE.png",
    },
    group: {
      name: "5 月日常迭代",
      link: "http://github.com/",
    },
    template1: "将",
    template2: "更新至已发布状态",
  },
  {
    id: "trend-5",
    updatedAt: "几秒前",
    user: {
      name: "朱偏右",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/ubnKSIfAJTxIgXOKlciN.png",
    },
    group: {
      name: "工程效能",
      link: "http://github.com/",
    },
    project: {
      name: "留言",
      link: "http://github.com/",
    },
    template1: "在",
    template2: "发布了",
  },
  {
    id: "trend-6",
    updatedAt: "几秒前",
    user: {
      name: "乐哥",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/jZUIxmJycoymBprLOUbT.png",
    },
    group: {
      name: "程序员日常",
      link: "http://github.com/",
    },
    project: {
      name: "品牌迭代",
      link: "http://github.com/",
    },
    template1: "在",
    template2: "新建项目",
  },
];

// 金额格式化函数
const formatAmount = (value) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0.00'
  }
  return Number(value).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
};

// 资金曲线相关
const equityChartContainer = ref(null);
let equityChart = null;
const equityChartData = ref({
  dates: [],
  hyEquity: [],
  hsEquity: [],
  totalEquity: [],
  hyWithdrawalDepositTotal: [], // hy账户存取合计
  hsWithdrawalDepositTotal: []  // hs账户存取合计
});
const originalData = ref(null); // 保存原始数据存储原始数据以便切换

// 获取资金曲线数据
async function fetchEquityChartData() {
  try {
    // 创建查询参数副本
    const params = {
      pageNum: 1,
      pageSize: 1000, // 获取足够多的数据用于图表
      accountCode: undefined, // 不限制账户，获取所有账户数据
      beginDate: undefined, // 默认获取所有数据
      endDate: undefined
    }

    const response = await listFutureAccountDaily(params)
    if (response.code === 200) {
      const data = response.data?.rows || response.rows || []
      
      // 按日期分组
      const groupedByDate = {}
      data.forEach(item => {
        if (!groupedByDate[item.settlementDate]) {
          groupedByDate[item.settlementDate] = {
            hy: 0,
            hs: 0,
            hyWithdrawalDeposit: 0,
            hsWithdrawalDeposit: 0
          }
        }
        if (item.accountCode === 'hy') {
          groupedByDate[item.settlementDate].hy = Number(item.equity) || 0
          groupedByDate[item.settlementDate].hyWithdrawalDeposit = Number(item.withdrawal_deposit_total) || 0
        } else if (item.accountCode === 'hs') {
          groupedByDate[item.settlementDate].hs = Number(item.equity) || 0
          groupedByDate[item.settlementDate].hsWithdrawalDeposit = Number(item.withdrawal_deposit_total) || 0
        }
      })

      // 转换为数组并排序
      const dates = Object.keys(groupedByDate).sort()
      const hyEquity = []
      const hsEquity = []
      const totalEquity = []
      const hyWithdrawalDepositTotal = []
      const hsWithdrawalDepositTotal = []

      dates.forEach(date => {
        hyEquity.push(groupedByDate[date].hy)
        hsEquity.push(groupedByDate[date].hs)
        totalEquity.push(groupedByDate[date].hy + groupedByDate[date].hs)
        hyWithdrawalDepositTotal.push(groupedByDate[date].hyWithdrawalDeposit)
        hsWithdrawalDepositTotal.push(groupedByDate[date].hsWithdrawalDeposit)
      })

      // 存储原始数据
      originalData.value = {
        dates: [...dates],
        hyEquity: [...hyEquity],
        hsEquity: [...hsEquity],
        totalEquity: [...totalEquity],
        hyWithdrawalDepositTotal: [...hyWithdrawalDepositTotal],
        hsWithdrawalDepositTotal: [...hsWithdrawalDepositTotal]
      }

      equityChartData.value = {
        dates,
        hyEquity,
        hsEquity,
        totalEquity,
        hyWithdrawalDepositTotal,
        hsWithdrawalDepositTotal
      }

      return true
    }
    return false
  } catch (error) {
    console.error('获取资金曲线数据失败:', error)
    ElMessage.error('获取资金曲线数据失败，请稍后重试')
    return false
  }
}

// 初始化资金曲线图表
function initEquityChart() {
  try {
    if (equityChart) {
      equityChart.dispose()
      equityChart = null
    }

    const chartDom = equityChartContainer.value
    if (!chartDom) {
      console.warn('资金曲线容器未找到');
      return
    }

    equityChart = echarts.init(chartDom)

    // 计算Y轴的动态范围，使曲线变化更加明显
    // 只使用totalEquity数据，因为我们只显示合计金额
    const totalEquityData = equityChartData.value?.totalEquity || [];
    const allValues = totalEquityData.filter(v => v !== undefined && v !== null && v > 0);
    
    // 处理空数据情况
    if (allValues.length === 0) {
      // 如果没有有效数据，设置默认范围
      console.log('资金曲线：无有效数据，使用默认范围');
      const option = {
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: equityChartData.value?.dates || [],
          axisLabel: {
            rotate: 45,
            fontSize: 11
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: function(value) {
              return formatAmount(value)
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              opacity: 0.6
            }
          }
        },
        series: []
      };
      
      equityChart.setOption(option, true);
      return;
    }
    
    // 优化的Y轴范围计算逻辑
    const minValue = Math.min(...allValues);
    const maxValue = Math.max(...allValues);
    const range = maxValue - minValue;
    
    // 智能Y轴范围计算
    let yAxisMin, yAxisMax;
    
    if (range === 0) {
      // 处理所有值都相同的情况
      const baseValue = minValue || 10000; // 避免0值
      // 根据数据量级调整扩展比例，小数值给予更大扩展
      const scaleFactor = baseValue < 10000 ? 0.2 : 0.1;
      yAxisMin = baseValue * (1 - scaleFactor);
      yAxisMax = baseValue * (1 + scaleFactor);
    } else {
      // 计算数据变化百分比
      const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
      
      // 根据数据变化幅度和实际值大小动态调整扩展比例
      let lowerPadding, upperPadding;
      
      // 智能扩展比例计算
      if (variationRatio < 0.01) { // 变化小于1%
        // 极小变化，需要较大扩展以显示趋势
        lowerPadding = 0.4; // 向下40%
        upperPadding = 0.4; // 向上40%
      } else if (variationRatio < 0.05) { // 变化小于5%
        // 小幅变化，中等扩展
        lowerPadding = 0.25; // 向下25%
        upperPadding = 0.25; // 向上25%
      } else if (variationRatio < 0.2) { // 变化小于20%
        // 中幅变化，适度扩展
        lowerPadding = 0.15; // 向下15%
        upperPadding = 0.15; // 向上15%
      } else {
        // 大幅变化，保持较小扩展以突出主要趋势
        lowerPadding = 0.08; // 向下8%
        upperPadding = 0.08; // 向上8%
      }
      
      // 计算最终Y轴范围
      yAxisMin = minValue - range * lowerPadding;
      yAxisMax = maxValue + range * upperPadding;
      
      // 对于大数值，添加额外的平滑处理，避免范围过大
      const avgValue = (minValue + maxValue) / 2;
      if (avgValue > 100000 && variationRatio > 0.3) {
        // 大数值且变化大时，稍微缩小范围
        const centerPadding = range * 0.05;
        yAxisMin += centerPadding;
        yAxisMax -= centerPadding;
      }
    }
    
    // 确保最小值不会小于0，并且至少留有一定空间
    yAxisMin = Math.max(0, Math.floor(yAxisMin * 0.98));
    // 对最大值进行轻微调整，确保曲线不会紧贴顶部
    yAxisMax = Math.ceil(yAxisMax * 1.02);
    
    // 添加调试日志，以便验证Y轴范围计算结果
    const variationRatio = range > 0 ? range / Math.max(Math.abs(minValue), Math.abs(maxValue)) : 0;
    console.log('资金曲线Y轴范围计算:', {
      dataRange: { min: minValue, max: maxValue, range: range },
      variationRatio: variationRatio,
      finalAxisRange: { min: yAxisMin, max: yAxisMax }
    });

    // 根据数据变化动态调整X轴显示范围
    // 找出第一个和最后一个非零数据点的索引
    const totalEquity = totalEquityData;
    let startIdx = 0;
    let endIdx = totalEquity.length - 1;
    
    // 寻找第一个非零数据点
    for (let i = 0; i < totalEquity.length; i++) {
      if (totalEquity[i] && totalEquity[i] > 0) {
        startIdx = Math.max(0, i - 1); // 留一个额外的数据点作为缓冲
        break;
      }
    }
    
    // 寻找最后一个非零数据点
    for (let i = totalEquity.length - 1; i >= 0; i--) {
      if (totalEquity[i] && totalEquity[i] > 0) {
        endIdx = Math.min(totalEquity.length - 1, i + 1); // 留一个额外的数据点作为缓冲
        break;
      }
    }
    
    // 计算数据显示比例
    const totalPoints = totalEquity.length;
    const visiblePoints = endIdx - startIdx + 1;
    
    // 设置默认显示范围，如果数据点太少则显示全部
    let startPercent = 0;
    let endPercent = 100;
    
    // 如果有足够的数据点，根据实际数据范围调整显示
    if (totalPoints > 7 && visiblePoints < totalPoints * 0.8) {
      // 将范围稍微扩大一点，以便更好地查看上下文
      const adjustedStart = Math.max(0, startIdx - Math.floor(totalPoints * 0.05));
      const adjustedEnd = Math.min(totalPoints - 1, endIdx + Math.floor(totalPoints * 0.05));
      
      startPercent = (adjustedStart / totalPoints) * 100;
      endPercent = ((adjustedEnd + 1) / totalPoints) * 100;
    }

    const option = {
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: {
          color: '#333'
        },
        formatter: function(params) {
          if (!params || !params[0]) return '';
          return params[0].axisValue + '<br/>' + 
                 params[0].marker + params[0].seriesName + ': ' + formatAmount(params[0].value);
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '5%',
        containLabel: true
      },
      // 添加数据缩放组件
      dataZoom: [
          {
            type: 'inside', // 内置缩放组件，支持鼠标滚轮缩放
            start: startPercent,
            end: endPercent,
            zoomOnMouseWheel: true,
            moveOnMouseMove: true
          },
        {
          type: 'slider', // 底部滑动条缩放组件
          start: startPercent,
          end: endPercent,
          height: 20,
          bottom: 5,
          textStyle: {
            fontSize: 10
          },
          borderColor: '#ddd'
        }
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: equityChartData.value?.dates || [],
        axisLabel: {
          rotate: 45,
          fontSize: 11
        }
      },
      yAxis: {
        type: 'value',
        min: yAxisMin,
        max: yAxisMax,
        axisLabel: {
          formatter: function(value) {
            return formatAmount(value)
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            opacity: 0.6
          }
        }
      },
      series: [
        {
          name: '合计',
          type: 'line',
          data: totalEquityData,
          smooth: true,
          lineStyle: {
            width: 3,
            type: 'solid',
            color: '#ee6666'
          },
          symbol: 'circle',
          symbolSize: 4,
          emphasis: {
            focus: 'series'
          }
        }
      ]
    }

    // 使用true参数强制完全替换当前option
    equityChart.setOption(option, true)

    // 不再需要图例选择事件监听
    // 添加dataZoom事件监听，当X轴范围变化时同步更新Y轴范围
    equityChart.off('dataZoom');
    equityChart.on('dataZoom', handleDataZoom);

    // 响应式调整
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('初始化资金曲线图表时出错:', error);
  }
}

// 单独的调整大小处理函数
  function handleResize() {
    try {
      equityChart?.resize()
    } catch (error) {
      console.error('调整图表大小时出错:', error);
    }
  }

  // 处理X轴选择范围变化，同步更新Y轴范围
  function handleDataZoom(params) {
    try {
      if (!equityChart || !equityChartData.value?.totalEquity) return;

      const start = params.start / 100;
      const end = params.end / 100;
      const data = equityChartData.value.totalEquity;
      const startIndex = Math.floor(start * data.length);
      const endIndex = Math.ceil(end * data.length);
      
      // 获取当前可见范围内的数据
      const visibleData = data.slice(startIndex, endIndex + 1);
      const validData = visibleData.filter(v => v !== undefined && v !== null && v > 0);
      
      if (validData.length === 0) return;
      
      // 重新计算Y轴范围
      const minValue = Math.min(...validData);
      const maxValue = Math.max(...validData);
      const range = maxValue - minValue;
      
      let yAxisMin, yAxisMax;
      
      if (range === 0) {
        const baseValue = minValue || 10000;
        const scaleFactor = baseValue < 10000 ? 0.2 : 0.1;
        yAxisMin = baseValue * (1 - scaleFactor);
        yAxisMax = baseValue * (1 + scaleFactor);
      } else {
        const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
        
        let lowerPadding, upperPadding;
        if (variationRatio < 0.01) {
          lowerPadding = 0.4;
          upperPadding = 0.4;
        } else if (variationRatio < 0.05) {
          lowerPadding = 0.25;
          upperPadding = 0.25;
        } else if (variationRatio < 0.2) {
          lowerPadding = 0.15;
          upperPadding = 0.15;
        } else {
          lowerPadding = 0.08;
          upperPadding = 0.08;
        }
        
        yAxisMin = minValue - range * lowerPadding;
        yAxisMax = maxValue + range * upperPadding;
        
        const avgValue = (minValue + maxValue) / 2;
        if (avgValue > 100000 && variationRatio > 0.3) {
          const centerPadding = range * 0.05;
          yAxisMin += centerPadding;
          yAxisMax -= centerPadding;
        }
      }
      
      yAxisMin = Math.max(0, Math.floor(yAxisMin * 0.98));
      yAxisMax = Math.ceil(yAxisMax * 1.02);
      
      // 更新Y轴范围
      equityChart.setOption({
        yAxis: {
          min: yAxisMin,
          max: yAxisMax
        }
      });
    } catch (error) {
      console.error('处理dataZoom事件时出错:', error);
    }
  }

// 处理图例选择变化，动态调整Y轴范围
function handleLegendSelectChanged(params) {
  // 获取当前所有系列的显示状态
  const selectedSeries = params.selected;
  const visibleValues = [];
  
  // 收集当前可见系列的数据
  if (selectedSeries['hy账户']) {
    visibleValues.push(...equityChartData.value.hyEquity);
  }
  if (selectedSeries['hs账户']) {
    visibleValues.push(...equityChartData.value.hsEquity);
  }
  if (selectedSeries['合计']) {
    visibleValues.push(...equityChartData.value.totalEquity);
  }
  
  // 如果没有可见数据，不调整Y轴
  if (visibleValues.length === 0 || visibleValues.every(v => v === 0)) {
    return;
  }
  
  // 基于可见数据重新计算Y轴范围
  const minValue = Math.min(...visibleValues);
  const maxValue = Math.max(...visibleValues);
  const range = maxValue - minValue;
  
  // 计算新的Y轴范围
  let yAxisMin, yAxisMax;
  
  if (range === 0) {
    // 处理所有值都相同的情况
    const baseValue = minValue || 10000; // 避免0值
    yAxisMin = baseValue * 0.9; // 向下10%
    yAxisMax = baseValue * 1.1; // 向上10%
  } else {
    // 根据数据变化幅度动态调整扩展比例
    const variationRatio = range / Math.max(Math.abs(minValue), Math.abs(maxValue));
    
    if (variationRatio < 0.01) { // 变化小于1%
      // 数据变化非常小，需要更大的扩展比例
      yAxisMin = minValue - range * 0.5; // 向下50%
      yAxisMax = maxValue + range * 0.5; // 向上50%
    } else if (variationRatio < 0.05) { // 变化小于5%
      // 数据变化较小，适度扩展
      yAxisMin = minValue - range * 0.3; // 向下30%
      yAxisMax = maxValue + range * 0.3; // 向上30%
    } else {
      // 正常数据范围
      yAxisMin = minValue - range * 0.1; // 向下10%
      yAxisMax = maxValue + range * 0.1; // 向上10%
    }
  }
  
  // 确保最小值不会小于0
  yAxisMin = Math.max(0, yAxisMin);
  
  try {
    // 使用更安全的方式更新Y轴范围
    equityChart.dispatchAction({
      type: 'dataZoom',
      start: 0,
      end: 100
    });
    
    // 延迟一下再更新Y轴，确保图表状态稳定
    setTimeout(() => {
      if (equityChart) {
        equityChart.setOption({
          yAxis: {
            min: yAxisMin,
            max: yAxisMax
          }
        }, false); // 使用false避免强制重绘
      }
    }, 50);
  } catch (error) {
    console.error('更新Y轴范围时出错:', error);
  }
}

// 前复权计算函数
function calculateForwardFilled() {
  if (!originalData.value) return;
  
  try {
    const { dates, hyEquity, hsEquity, hyWithdrawalDepositTotal, hsWithdrawalDepositTotal } = originalData.value;
    // 添加安全检查
    if (!dates || !hyEquity || !hsEquity) return;
    
    const filledHyEquity = [...hyEquity];
    const filledHsEquity = [...hsEquity];
    const filledTotalEquity = [];
    
    // 从后往前遍历计算前复权值
    let hyAdjustment = 0;
    let hsAdjustment = 0;
    
    // 从最后一天开始，从后往前计算
    for (let i = dates.length - 1; i >= 0; i--) {
      // 对于最后一天，不需要调整
      if (i === dates.length - 1) {
        filledHyEquity[i] = hyEquity[i] || 0;
        filledHsEquity[i] = hsEquity[i] || 0;
      } else {
        // 从后往前累计存取合计的调整量，增加安全检查
        const nextHyWithdrawal = i + 1 < (hyWithdrawalDepositTotal?.length || 0) ? hyWithdrawalDepositTotal[i + 1] : 0;
        const currHyWithdrawal = i < (hyWithdrawalDepositTotal?.length || 0) ? hyWithdrawalDepositTotal[i] : 0;
        const nextHsWithdrawal = i + 1 < (hsWithdrawalDepositTotal?.length || 0) ? hsWithdrawalDepositTotal[i + 1] : 0;
        const currHsWithdrawal = i < (hsWithdrawalDepositTotal?.length || 0) ? hsWithdrawalDepositTotal[i] : 0;
        
        hyAdjustment += (nextHyWithdrawal || 0) - (currHyWithdrawal || 0);
        hsAdjustment += (nextHsWithdrawal || 0) - (currHsWithdrawal || 0);
        
        // 应用调整量
        filledHyEquity[i] = (hyEquity[i] || 0) + hyAdjustment;
        filledHsEquity[i] = (hsEquity[i] || 0) + hsAdjustment;
      }
      
      // 确保值不为负数
      filledHyEquity[i] = Math.max(0, filledHyEquity[i]);
      filledHsEquity[i] = Math.max(0, filledHsEquity[i]);
      
      // 计算合计值
      filledTotalEquity[i] = filledHyEquity[i] + filledHsEquity[i];
    }
    
    // 更新图表数据
    equityChartData.value = {
      ...equityChartData.value,
      hyEquity: filledHyEquity,
      hsEquity: filledHsEquity,
      totalEquity: filledTotalEquity
    };
  } catch (error) {
    console.error('计算前复权数据时出错:', error);
  }
}

// 不再需要切换复权状态的功能

// 初始化资金曲线
async function initDashboardEquityChart() {
  try {
    const success = await fetchEquityChartData();
    if (success) {
      // 默认使用前复权数据
      calculateForwardFilled();
      await nextTick();
      initEquityChart();
    } else {
      // 如果获取数据失败，初始化一个空图表
      await nextTick();
      initEquityChart();
    }
  } catch (error) {
    console.error('初始化资金曲线失败:', error);
    // 即使出错也尝试初始化一个空图表，避免影响页面其他部分
    try {
      await nextTick();
      initEquityChart();
    } catch (initError) {
      console.error('初始化空图表也失败:', initError);
    }
  }
}

const radarContainer = ref();
const radarData = [
  {
    name: "个人",
    label: "引用",
    value: 10,
  },
  {
    name: "个人",
    label: "口碑",
    value: 8,
  },
  {
    name: "个人",
    label: "产量",
    value: 4,
  },
  {
    name: "个人",
    label: "贡献",
    value: 5,
  },
  {
    name: "个人",
    label: "热度",
    value: 7,
  },
  {
    name: "团队",
    label: "引用",
    value: 3,
  },
  {
    name: "团队",
    label: "口碑",
    value: 9,
  },
  {
    name: "团队",
    label: "产量",
    value: 6,
  },
  {
    name: "团队",
    label: "贡献",
    value: 3,
  },
  {
    name: "团队",
    label: "热度",
    value: 1,
  },
  {
    name: "部门",
    label: "引用",
    value: 4,
  },
  {
    name: "部门",
    label: "口碑",
    value: 1,
  },
  {
    name: "部门",
    label: "产量",
    value: 6,
  },
  {
    name: "部门",
    label: "贡献",
    value: 5,
  },
  {
    name: "部门",
    label: "热度",
    value: 7,
  },
];
let radar;
onMounted(async () => {
  try {
    // 初始化账户信息
    await fetchLatestAccountData();
    
    // 初始化资金曲线图表
    await initDashboardEquityChart();
    
    // 初始化雷达图
    nextTick(() => {
      try {
        if (radarContainer.value) {
          radar = new Radar(radarContainer.value, {
            data: radarData,
            xField: "label",
            yField: "value",
            seriesField: "name",
            point: {
              size: 4,
            },
            legend: {
              layout: "horizontal",
              position: "bottom",
            },
          });
          radar.render();
        }
      } catch (radarError) {
        console.error('初始化雷达图时出错:', radarError);
      }
    });
  } catch (error) {
    console.error('mounted钩子执行时出错:', error);
  }
});

onBeforeUnmount(() => {
  try {
    radar?.destroy?.();
    // 销毁资金曲线图表并移除事件监听
    if (equityChart) {
      equityChart.off('dataZoom', handleDataZoom);
      equityChart.dispose();
      equityChart = null;
    }
    window.removeEventListener('resize', handleResize);
  } catch (error) {
    console.error('组件卸载时出错:', error);
  }
});
</script>

<style scoped lang="less">
.textOverflow() {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  word-break: break-all;
}

// mixins for clearfix
// ------------------------
.clearfix() {
  zoom: 1;
  &::before,
  &::after {
    display: table;
    content: " ";
  }
  &::after {
    clear: both;
    height: 0;
    font-size: 0;
    visibility: hidden;
  }
}

.activitiesList {
  padding: 0 24px 8px 24px;
  .username {
    color: rgba(0, 0, 0, 0.65);
  }
  .event {
    font-weight: normal;
  }
}

.pageHeaderContent {
  display: flex;
  padding: 12px;
  margin-bottom: 24px;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;
  .avatar {
    flex: 0 1 72px;
    & > span {
      display: block;
      width: 72px;
      height: 72px;
      border-radius: 72px;
    }
  }
  .content {
    position: relative;
    top: 4px;
    flex: 1 1 auto;
    margin-left: 24px;
    color: rgba(0, 0, 0, 0.45);
    line-height: 22px;
    .contentTitle {
      margin-bottom: 12px;
      color: rgba(0, 0, 0, 0.85);
      font-weight: 500;
      font-size: 20px;
      line-height: 28px;
    }
  }
}

.extraContent {
  .clearfix();

  float: right;
  white-space: nowrap;
  .statItem {
    position: relative;
    display: inline-block;
    padding: 0 32px;
    > p:first-child {
      margin-bottom: 4px;
      color: rgba(0, 0, 0, 0.45);
      font-size: 14px;
      line-height: 22px;
    }
    > p {
      margin: 0;
      color: rgba(0, 0, 0, 0.85);
      font-size: 30px;
      line-height: 38px;
      > span {
        color: rgba(0, 0, 0, 0.45);
        font-size: 20px;
      }
    }
    &::after {
      position: absolute;
      top: 8px;
      right: 0;
      width: 1px;
      height: 40px;
      background-color: #e8e8e8;
      content: "";
    }
    &:last-child {
      padding-right: 0;
      &::after {
        display: none;
      }
    }
  }
}

.members {
  a {
    display: block;
    height: 24px;
    margin: 12px 0;
    color: rgba(0, 0, 0, 0.65);
    transition: all 0.3s;
    .textOverflow();
    .member {
      margin-left: 12px;
      font-size: 14px;
      line-height: 24px;
      vertical-align: top;
    }
    &:hover {
      color: #1890ff;
    }
  }
}

.projectList {
  :deep(.ant-card-meta-description) {
    height: 44px;
    overflow: hidden;
    color: rgba(0, 0, 0, 0.45);
    line-height: 22px;
  }
  .cardTitle {
    font-size: 0;
    a {
      display: inline-block;
      height: 24px;
      margin-left: 12px;
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
      line-height: 24px;
      vertical-align: top;
      &:hover {
        color: #1890ff;
      }
    }
  }
  .projectGrid {
    width: 33.33%;
  }
  .projectItemContent {
    display: flex;
    flex-basis: 100%;
    height: 20px;
    margin-top: 8px;
    overflow: hidden;
    font-size: 12px;
    line-height: 20px;
    .textOverflow();
    a {
      display: inline-block;
      flex: 1 1 0;
      color: rgba(0, 0, 0, 0.45);
      .textOverflow();
      &:hover {
        color: #1890ff;
      }
    }
    .datetime {
      flex: 0 0 auto;
      float: right;
      color: rgba(0, 0, 0, 0.25);
    }
  }
}

.datetime {
  color: rgba(0, 0, 0, 0.25);
}

@media screen and (max-width: 1200px) and (min-width: 992px) {
  .activeCard {
    margin-bottom: 24px;
  }
  .members {
    margin-bottom: 0;
  }
  .extraContent {
    margin-left: -44px;
    .statItem {
      padding: 0 16px;
    }
  }
}

@media screen and (max-width: 992px) {
  .activeCard {
    margin-bottom: 24px;
  }
  .members {
    margin-bottom: 0;
  }
  .extraContent {
    float: none;
    margin-right: 0;
    .statItem {
      padding: 0 16px;
      text-align: left;
      &::after {
        display: none;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .extraContent {
    margin-left: -16px;
  }
  .projectList {
    .projectGrid {
      width: 50%;
    }
  }
}

@media screen and (max-width: 576px) {
  .pageHeaderContent {
    display: block;
    .content {
      margin-left: 0;
    }
  }
  .extraContent {
    .statItem {
      float: none;
    }
  }
}

@media screen and (max-width: 480px) {
  .projectList {
    .projectGrid {
      width: 100%;
    }
  }
}

.equity-chart-container {
  .textOverflow();
}
</style>